package com.ciwong.epaper.util.KHBVideo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.ciwong.epaper.modules.evaluate.ui.UserDKWorkActivity;
import com.ciwong.epaper.modules.evaluate.ui.UserDkSubmitActivity;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.epaper.R;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by PLA-BYOU on 2017/10/31.
 */
public abstract class KHBVideoPlayer extends FrameLayout
        implements View.OnClickListener, SeekBar.OnSeekBarChangeListener,
        View.OnTouchListener {

    public static final String TAG = "KHBVideoPlayer";

    public static final int THRESHOLD = 80;

    public static final int FULL_SCREEN_NORMAL_DELAY = 300;

    public static final int SCREEN_LAYOUT_NORMAL = 0;

    public static final int SCREEN_LAYOUT_LIST = 1;

    public static final int SCREEN_WINDOW_FULLSCREEN = 2;

    public static final int SCREEN_WINDOW_TINY = 3;
    /**
     * 有声音
     */
    public static final int PLAY_MODE_UNMUTE = 0;
    /**
     * 静音
     */
    public static final int PLAY_MODE_MUTE = 1;

    public static final int CURRENT_STATE_NORMAL = 0;

    public static final int CURRENT_STATE_PREPARING = 1;

    public static final int CURRENT_STATE_PREPARING_CHANGING_URL = 2;

    public static final int CURRENT_STATE_PLAYING = 3;

    public static final int CURRENT_STATE_PAUSE = 5;

    public static final int CURRENT_STATE_AUTO_COMPLETE = 6;

    public static final int CURRENT_STATE_ERROR = 7;

    public static final String URL_KEY_DEFAULT = "URL_KEY_DEFAULT";

    public static boolean ACTION_BAR_EXIST = true;

    public static boolean TOOL_BAR_EXIST = true;

    public static int FULLSCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_SENSOR;

    public static int NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;

    public static boolean SAVE_PROGRESS = true;

    public static boolean WIFI_TIP_DIALOG_SHOWED = false;

    public static long CLICK_QUIT_FULLSCREEN_TIME = 0;

    public static long lastAutoFullscreenTime = 0;

    public static AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {// 是否新建个class，代码更规矩，并且变量的位置也很尴尬
        @Override
        public void onAudioFocusChange(int focusChange) {
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_GAIN:
                    break;
                case AudioManager.AUDIOFOCUS_LOSS:
                    releaseAllVideos();
                    // CWLog.d(TAG, "AUDIOFOCUS_LOSS [" + this.hashCode() +
                    // "]");
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    try {
                        if (KHBMediaManager.instance().mediaPlayer != null
                                && KHBMediaManager.instance().mediaPlayer
                                .isPlaying()) {
                            KHBMediaManager.instance().mediaPlayer.pause();
                        }
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    }
                    // CWLog.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT [" +
                    // this.hashCode()
                    // + "]");
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    break;
            }
        }
    };

    protected static KHBUserAction JZ_USER_EVENT;

    protected static Timer UPDATE_PROGRESS_TIMER;

    public int currentState = -1;

    public int currentScreen = -1;

    public int currentPlayMode = PLAY_MODE_UNMUTE;

    public boolean loop = false;

    public Map<String, String> headData;

    // public String url = "";
    public Object[] objects = null;

    public int seekToInAdvance = 0;

    public ImageView startButton;

    public SeekBar progressBar;

    public ImageView fullscreenButton;

    public TextView currentTimeTextView, totalTimeTextView;

    public ViewGroup textureViewContainer;

    public ViewGroup topContainer, bottomContainer;

    public int widthRatio = 0;

    public int heightRatio = 0;

    protected boolean isVideoRendingStart = false;

    protected int mScreenWidth;

    protected int mScreenHeight;

    protected AudioManager mAudioManager;

    protected Handler mHandler;

    protected ProgressTimerTask mProgressTimerTask;

    protected boolean mTouchingProgressBar;

    protected float mDownX;

    protected float mDownY;

    protected boolean mChangeVolume;

    protected boolean mChangePosition;

    protected boolean mChangeBrightness;

    protected int mGestureDownPosition;

    protected int mGestureDownVolume;

    protected float mGestureDownBrightness;

    protected int mSeekTimePosition;

    public LinkedHashMap urlMap;

    public int currentUrlMapIndex = 0;

    public int positionInList = -1;

    public boolean isViewPostVideo = false;

    public String topicPostId;

    private int type;

    private Context mContext;

    public KHBVideoPlayer(Context context) {
        super(context);
        init(context);
    }

    public KHBVideoPlayer(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public static void releaseAllVideos() {
        if ((System.currentTimeMillis()
                - CLICK_QUIT_FULLSCREEN_TIME) > FULL_SCREEN_NORMAL_DELAY) {
            // CWLog.d(TAG, "releaseAllVideos");
            KHBVideoPlayerManager.completeAll();
            KHBMediaManager.instance().positionInList = -1;
            KHBMediaManager.instance().releaseMediaPlayer();
        }
    }

    public static void startFullscreen(Context context, Class _class,
                                       String url, int playMode, Object... objects) {
        LinkedHashMap map = new LinkedHashMap();
        map.put(URL_KEY_DEFAULT, url);
        startFullscreen(context, _class, map, 0, playMode, objects);
    }

    public static void startFullscreen(Context context, Class _class,
                                       LinkedHashMap urlMap, int defaultUrlMapIndex, int playMode, Object... objects) {
        hideSupportActionBar(context);
        KHBUtils.setRequestedOrientation(context, FULLSCREEN_ORIENTATION);
        ViewGroup vp = (ViewGroup) (KHBUtils.scanForActivity(context))// .getWindow().getDecorView();
                .findViewById(Window.ID_ANDROID_CONTENT);
        View old = vp.findViewById(R.id.jz_fullscreen_id);
        if (old != null) {
            vp.removeView(old);
        }
        try {
            Constructor<KHBVideoPlayer> constructor = _class
                    .getConstructor(Context.class);
            final KHBVideoPlayer KHBVideoPlayer = constructor
                    .newInstance(context);
            KHBVideoPlayer.setId(R.id.jz_fullscreen_id);
            LayoutParams lp = new LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            vp.addView(KHBVideoPlayer, lp);
            // final Animation ra = AnimationUtils.loadAnimation(context,
            // R.anim.start_fullscreen);
            // jzVideoPlayer.setAnimation(ra);
            KHBVideoPlayer.setUp(urlMap, defaultUrlMapIndex,
                    KHBVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN, playMode, objects);
            CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
            KHBVideoPlayer.startButton.performClick();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getCurrentUrl() {
        return KHBUtils.getCurrentUrlFromMap(urlMap, currentUrlMapIndex);
    }

    public static boolean backPress() {
        // CWLog.i(TAG, "backPress");
        if ((System.currentTimeMillis()
                - CLICK_QUIT_FULLSCREEN_TIME) < FULL_SCREEN_NORMAL_DELAY)
            return false;
        if (KHBVideoPlayerManager.getSecondFloor() != null) {
            CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
            if (KHBVideoPlayerManager.getFirstFloor().getCurrentUrl()
                    .equals(KHBMediaManager.CURRENT_PLAYING_URL)) {
                KHBVideoPlayer KHBVideoPlayer = KHBVideoPlayerManager
                        .getSecondFloor();
                KHBVideoPlayer.onEvent(
                        KHBVideoPlayer.currentScreen == KHBVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN
                                ? KHBUserAction.ON_QUIT_FULLSCREEN
                                : KHBUserAction.ON_QUIT_TINYSCREEN);
                KHBVideoPlayerManager.getFirstFloor().playOnThisJzvd();
            } else {
                // 直接退出全屏和小窗
                KHBVideoPlayerManager
                        .getCurrentJzvd().currentState = CURRENT_STATE_NORMAL;
                KHBVideoPlayerManager.getFirstFloor().clearFloatScreen();
                KHBMediaManager.instance().releaseMediaPlayer();
                KHBVideoPlayerManager.setFirstFloor(null);
            }
            return true;
        } else if (KHBVideoPlayerManager.getFirstFloor() != null
                && (KHBVideoPlayerManager
                .getFirstFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN
                || KHBVideoPlayerManager
                .getFirstFloor().currentScreen == SCREEN_WINDOW_TINY)) {// 以前我总想把这两个判断写到一起，这分明是两个独立是逻辑
            CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
            // 直接退出全屏和小窗
            KHBVideoPlayerManager
                    .getCurrentJzvd().currentState = CURRENT_STATE_NORMAL;
            KHBVideoPlayerManager.getFirstFloor().clearFloatScreen();
            KHBMediaManager.instance().releaseMediaPlayer();
            KHBVideoPlayerManager.setFirstFloor(null);
            return true;
        }
        return false;
    }

    public static void showSupportActionBar(Context context) {
        // if (ACTION_BAR_EXIST && KHBUtils.getAppCompActivity(context) != null)
        // {
        // ActionBar ab =
        // KHBUtils.getAppCompActivity(context).getSupportActionBar();
        // if (ab != null) {
        // ab.setShowHideAnimationEnabled(false);
        // ab.show();
        // }
        // }
        if (TOOL_BAR_EXIST) {
            KHBUtils.getWindow(context)
                    .clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

    public static void hideSupportActionBar(Context context) {
        // if (ACTION_BAR_EXIST && KHBUtils.getAppCompActivity(context) != null)
        // {
        // ActionBar ab =
        // KHBUtils.getAppCompActivity(context).getSupportActionBar();
        // if (ab != null) {
        // ab.setShowHideAnimationEnabled(false);
        // ab.hide();
        // }
        // }
        if (TOOL_BAR_EXIST) {
            KHBUtils.getWindow(context).setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

    public static void clearSavedProgress(Context context, String url) {
        KHBUtils.clearSavedProgress(context, url);
    }

    public static void setJzUserAction(KHBUserAction jzUserEvent) {
        JZ_USER_EVENT = jzUserEvent;
    }

    public static void goOnPlayOnResume() {
        if (KHBVideoPlayerManager.getCurrentJzvd() != null) {
            KHBVideoPlayer jzvd = KHBVideoPlayerManager.getCurrentJzvd();
            if (jzvd.currentState == KHBVideoPlayer.CURRENT_STATE_PAUSE) {
                jzvd.onStatePlaying();
                KHBMediaManager.instance().mediaPlayer.start();
            }
        }
    }

    public static void goOnPlayOnPause() {
        if (KHBVideoPlayerManager.getCurrentJzvd() != null) {
            KHBVideoPlayer jzvd = KHBVideoPlayerManager.getCurrentJzvd();
            if (jzvd.currentState == KHBVideoPlayer.CURRENT_STATE_AUTO_COMPLETE
                    || jzvd.currentState == KHBVideoPlayer.CURRENT_STATE_NORMAL) {
                // JZVideoPlayer.releaseAllVideos();
            } else {
                jzvd.onStatePause();
                KHBMediaManager.instance().mediaPlayer.pause();
            }
        }
    }

    public abstract int getLayoutId();

    public void init(Context context) {
        this.mContext = context;
        View.inflate(context, getLayoutId(), this);
        startButton = (ImageView) findViewById(R.id.start);
        fullscreenButton = (ImageView) findViewById(R.id.fullscreen);
        progressBar = (SeekBar) findViewById(R.id.bottom_seek_progress);
        currentTimeTextView = (TextView) findViewById(R.id.current);
        totalTimeTextView = (TextView) findViewById(R.id.total);
        bottomContainer = (ViewGroup) findViewById(R.id.layout_bottom);
        textureViewContainer = (ViewGroup) findViewById(R.id.surface_container);
        topContainer = (ViewGroup) findViewById(R.id.layout_top);

        startButton.setOnClickListener(this);
        fullscreenButton.setOnClickListener(this);
        progressBar.setOnSeekBarChangeListener(this);
        bottomContainer.setOnClickListener(this);
        textureViewContainer.setOnClickListener(this);
        textureViewContainer.setOnTouchListener(this);

        mScreenWidth = getContext().getResources()
                .getDisplayMetrics().widthPixels;
        mScreenHeight = getContext().getResources()
                .getDisplayMetrics().heightPixels;
        mAudioManager = (AudioManager) getContext()
                .getSystemService(Context.AUDIO_SERVICE);
        mHandler = new Handler();

        try {
            if (isCurrentPlay()) {
                NORMAL_ORIENTATION = ((Activity) context)
                        .getRequestedOrientation();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setplsyModeUp(String url, int screen, int playMode, Object... objects) {
        LinkedHashMap map = new LinkedHashMap();
        map.put(URL_KEY_DEFAULT, url);
        setUp(map, 0, screen, playMode, objects);
    }

    public void setUp(LinkedHashMap urlMap, int defaultUrlMapIndex, int screen, int playMode,
                      Object... objects) {
        if (this.urlMap != null
                && !TextUtils.isEmpty(KHBUtils.getCurrentUrlFromMap(urlMap,
                currentUrlMapIndex))
                && TextUtils.equals(
                KHBUtils.getCurrentUrlFromMap(this.urlMap,
                        currentUrlMapIndex),
                KHBUtils.getCurrentUrlFromMap(urlMap,
                        currentUrlMapIndex))) {
            return;
        }
        if (isCurrentJZVD()
                && urlMap.containsValue(KHBMediaManager.CURRENT_PLAYING_URL)) {
            int position = 0;
            try {
                position = KHBMediaManager.instance().mediaPlayer
                        .getCurrentPosition();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
            if (position != 0) {
                KHBUtils.saveProgress(getContext(),
                        KHBMediaManager.CURRENT_PLAYING_URL, position);
            }
            KHBMediaManager.instance().releaseMediaPlayer();
        } else if (isCurrentJZVD()
                && !urlMap.containsValue(KHBMediaManager.CURRENT_PLAYING_URL)) {
            startWindowTiny();
        } else if (!isCurrentJZVD()
                && urlMap.containsValue(KHBMediaManager.CURRENT_PLAYING_URL)) {
            if (KHBVideoPlayerManager.getCurrentJzvd() != null
                    && KHBVideoPlayerManager
                    .getCurrentJzvd().currentScreen == KHBVideoPlayer.SCREEN_WINDOW_TINY) {
                // 需要退出小窗退到我这里，我这里是第一层级
                tmp_test_back = true;
            }
        } else if (!isCurrentJZVD()
                && !urlMap.containsValue(KHBMediaManager.CURRENT_PLAYING_URL)) {
        }
        this.urlMap = urlMap;
        this.currentUrlMapIndex = defaultUrlMapIndex;
        this.currentScreen = screen;
        this.currentPlayMode = playMode;
        this.objects = objects;
        this.headData = null;
        isVideoRendingStart = false;
        onStateNormal();

    }

    boolean tmp_test_back = false;

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.start) {
            // CWLog.i(TAG, "onClick start [" + this.hashCode() + "] ");

            if (urlMap == null || TextUtils.isEmpty(
                    KHBUtils.getCurrentUrlFromMap(urlMap, currentUrlMapIndex))) {
                Toast.makeText(getContext(),
                        getResources().getString(R.string.no_url),
                        Toast.LENGTH_SHORT).show();
                return;
            }
            if (currentState == CURRENT_STATE_NORMAL
                    || currentState == CURRENT_STATE_ERROR) {
                if (!KHBUtils.getCurrentUrlFromMap(urlMap, currentUrlMapIndex)
                        .startsWith("file")
                        && !KHBUtils.getCurrentUrlFromMap(urlMap,
                        currentUrlMapIndex).startsWith("/")
                        && !KHBUtils.isWifiConnected(getContext())
                        && !WIFI_TIP_DIALOG_SHOWED) {
                    showWifiDialog(KHBUserAction.ON_CLICK_START_ICON);
                    return;
                }
                startVideo(currentPlayMode);
                onEvent(currentState != CURRENT_STATE_ERROR
                        ? KHBUserAction.ON_CLICK_START_ICON
                        : KHBUserAction.ON_CLICK_START_ERROR);
            } else if (currentState == CURRENT_STATE_PLAYING) {
                onEvent(KHBUserAction.ON_CLICK_PAUSE);
                // CWLog.d(TAG, "pauseVideo [" + this.hashCode() + "] ");
                KHBMediaManager.instance().mediaPlayer.pause();
                onStatePause();
            } else if (currentState == CURRENT_STATE_PAUSE) {
                onEvent(KHBUserAction.ON_CLICK_RESUME);
                KHBMediaManager.instance().mediaPlayer.start();
                onStatePlaying();
            } else if (currentState == CURRENT_STATE_AUTO_COMPLETE) {
                onEvent(KHBUserAction.ON_CLICK_START_AUTO_COMPLETE);
                startVideo(currentPlayMode);
            }
        } else if (i == R.id.fullscreen) {
            // CWLog.i(TAG, "onClick fullscreen [" + this.hashCode() + "] ");
            if (currentState == CURRENT_STATE_AUTO_COMPLETE)
                return;
            if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
                // quit fullscreen
                backPress();
            } else {
                // CWLog.d(TAG, "toFullscreenActivity [" + this.hashCode() + "]
                // ");
                onEvent(KHBUserAction.ON_ENTER_FULLSCREEN);
                startWindowFullscreen();
//                ActivityJumpManager.jumpToOpenVideo((Activity) mContext,
//                        KHBUtils.getCurrentUrlFromMap(urlMap,
//                                currentUrlMapIndex),
//                        0);
            }
        } else if (i == R.id.surface_container
                && currentState == CURRENT_STATE_ERROR) {
            // CWLog.i(TAG, "onClick surfaceContainer State=Error ["
            // + this.hashCode() + "] ");
            startVideo(currentPlayMode);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        int id = v.getId();
        if (id == R.id.surface_container) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // CWLog.i(TAG, "onTouch surfaceContainer actionDown ["
                    // + this.hashCode() + "] ");
                    mTouchingProgressBar = true;

                    mDownX = x;
                    mDownY = y;
                    mChangeVolume = false;
                    mChangePosition = false;
                    mChangeBrightness = false;
                    break;
                case MotionEvent.ACTION_MOVE:
                    // CWLog.i(TAG, "onTouch surfaceContainer actionMove ["
                    // + this.hashCode() + "] ");
                    float deltaX = x - mDownX;
                    float deltaY = y - mDownY;
                    float absDeltaX = Math.abs(deltaX);
                    float absDeltaY = Math.abs(deltaY);
                    if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
                        if (!mChangePosition && !mChangeVolume
                                && !mChangeBrightness) {
                            if (absDeltaX > THRESHOLD || absDeltaY > THRESHOLD) {
                                cancelProgressTimer();
                                if (absDeltaX >= THRESHOLD) {
                                    // 全屏模式下的CURRENT_STATE_ERROR状态下,不响应进度拖动事件.
                                    // 否则会因为mediaplayer的状态非法导致App Crash
                                    if (currentState != CURRENT_STATE_ERROR) {
                                        mChangePosition = true;
                                        mGestureDownPosition = getCurrentPositionWhenPlaying();
                                    }
                                } else {
                                    // 如果y轴滑动距离超过设置的处理范围，那么进行滑动事件处理
                                    if (mDownX < mScreenWidth * 0.5f) {// 左侧改变亮度
                                        mChangeBrightness = true;
                                        WindowManager.LayoutParams lp = KHBUtils
                                                .getWindow(getContext())
                                                .getAttributes();
                                        if (lp.screenBrightness < 0) {
                                            try {
                                                mGestureDownBrightness = Settings.System
                                                        .getInt(getContext()
                                                                        .getContentResolver(),
                                                                Settings.System.SCREEN_BRIGHTNESS);
                                                // CWLog.i(TAG,
                                                // "current system brightness: "
                                                // + mGestureDownBrightness);
                                            } catch (Settings.SettingNotFoundException e) {
                                                e.printStackTrace();
                                            }
                                        } else {
                                            mGestureDownBrightness = lp.screenBrightness
                                                    * 255;
                                            // CWLog.i(TAG,
                                            // "current activity brightness: "
                                            // + mGestureDownBrightness);
                                        }
                                    } else {// 右侧改变声音
                                        mChangeVolume = true;
                                        mGestureDownVolume = mAudioManager
                                                .getStreamVolume(
                                                        AudioManager.STREAM_MUSIC);
                                    }
                                }
                            }
                        }
                    }
                    if (mChangePosition) {
                        int totalTimeDuration = getDuration();
                        mSeekTimePosition = (int) (mGestureDownPosition
                                + deltaX * totalTimeDuration / mScreenWidth);
                        if (mSeekTimePosition > totalTimeDuration)
                            mSeekTimePosition = totalTimeDuration;
                        String seekTime = KHBUtils
                                .stringForTime(mSeekTimePosition);
                        String totalTime = KHBUtils
                                .stringForTime(totalTimeDuration);

                        showProgressDialog(deltaX, seekTime, mSeekTimePosition,
                                totalTime, totalTimeDuration);
                    }
                    if (mChangeVolume) {
                        deltaY = -deltaY;
                        int max = mAudioManager
                                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                        int deltaV = (int) (max * deltaY * 3 / mScreenHeight);
                        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                                mGestureDownVolume + deltaV, 0);
                        // dialog中显示百分比
                        int volumePercent = (int) (mGestureDownVolume * 100
                                / max + deltaY * 3 * 100 / mScreenHeight);
                        showVolumeDialog(-deltaY, volumePercent);
                    }

                    if (mChangeBrightness) {
                        deltaY = -deltaY;
                        int deltaV = (int) (255 * deltaY * 3 / mScreenHeight);
                        WindowManager.LayoutParams params = KHBUtils
                                .getWindow(getContext()).getAttributes();
                        if (((mGestureDownBrightness + deltaV) / 255) >= 1) {// 这和声音有区别，必须自己过滤一下负值
                            params.screenBrightness = 1;
                        } else if (((mGestureDownBrightness + deltaV) / 255) <= 0) {
                            params.screenBrightness = 0.01f;
                        } else {
                            params.screenBrightness = (mGestureDownBrightness
                                    + deltaV) / 255;
                        }
                        KHBUtils.getWindow(getContext()).setAttributes(params);
                        // dialog中显示百分比
                        int brightnessPercent = (int) (mGestureDownBrightness
                                * 100 / 255 + deltaY * 3 * 100 / mScreenHeight);
                        showBrightnessDialog(brightnessPercent);
                        // mDownY = y;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    // CWLog.i(TAG, "onTouch surfaceContainer actionUp ["
                    // + this.hashCode() + "] ");
                    mTouchingProgressBar = false;
                    dismissProgressDialog();
                    dismissVolumeDialog();
                    dismissBrightnessDialog();
                    if (mChangePosition) {
                        onEvent(KHBUserAction.ON_TOUCH_SCREEN_SEEK_POSITION);
                        KHBMediaManager.instance().mediaPlayer
                                .seekTo(mSeekTimePosition);
                        int duration = getDuration();
                        int progress = mSeekTimePosition * 100
                                / (duration == 0 ? 1 : duration);
                        progressBar.setProgress(progress);
                    }
                    if (mChangeVolume) {
                        onEvent(KHBUserAction.ON_TOUCH_SCREEN_SEEK_VOLUME);
                    }
                    startProgressTimer();
                    break;
            }
        }
        return false;
    }

    public void startVideo(int currentPlayMode) {
//        stopMusic();
        KHBVideoPlayerManager.completeAll();
        this.seekToInAdvance = 0;
        CWLog.d(TAG, "startVideo [" + this.hashCode() + "] ");
        initTextureView();
        addTextureView();
        AudioManager mAudioManager = (AudioManager) getContext()
                .getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.requestAudioFocus(onAudioFocusChangeListener,
                AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
        KHBUtils.scanForActivity(getContext()).getWindow()
                .addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        KHBMediaManager.CURRENT_PLAYING_URL = KHBUtils
                .getCurrentUrlFromMap(urlMap, currentUrlMapIndex);
        KHBMediaManager.CURRENT_PLING_LOOP = loop;
        KHBMediaManager.MAP_HEADER_DATA = headData;
        onStatePreparing();
        KHBVideoPlayerManager.setFirstFloor(this);
        KHBMediaManager.instance().positionInList = positionInList;
        this.currentPlayMode = currentPlayMode;
        if (mContext instanceof UserDkSubmitActivity || mContext instanceof UserDKWorkActivity){
            startWindowFullscreen();
        }
    }

    public void onPrepared() {
        // CWLog.i(TAG, "onPrepared " + " [" + this.hashCode() + "] ");
        if (KHBUtils.getCurrentUrlFromMap(urlMap, currentUrlMapIndex)
                .toLowerCase().contains("mp3")) {
            onStatePrepared();
            onStatePlaying();
        }
    }

    public void setState(int state) {
        setState(state, 0, 0);
    }

    public void setState(int state, int urlMapIndex, int seekToInAdvance) {
        switch (state) {
            case CURRENT_STATE_NORMAL:
                onStateNormal();
                break;
            case CURRENT_STATE_PREPARING:
                onStatePreparing();
                break;
            case CURRENT_STATE_PREPARING_CHANGING_URL:
                onStatePreparingChangingUrl(urlMapIndex, seekToInAdvance);
                break;
            case CURRENT_STATE_PLAYING:
                onStatePlaying();
                break;
            case CURRENT_STATE_PAUSE:
                onStatePause();
                break;
            case CURRENT_STATE_ERROR:
                onStateError();
                break;
            case CURRENT_STATE_AUTO_COMPLETE:
                onStateAutoComplete();
                break;
        }
    }

    public void onStateNormal() {
        // CWLog.i(TAG, "onStateNormal " + " [" + this.hashCode() + "] ");
        currentState = CURRENT_STATE_NORMAL;
        cancelProgressTimer();
    }

    public void onStatePreparing() {
        // CWLog.i(TAG, "onStatePreparing " + " [" + this.hashCode() + "] ");
        currentState = CURRENT_STATE_PREPARING;
        resetProgressAndTime();
    }

    public void onStatePreparingChangingUrl(int urlMapIndex,
                                            int seekToInAdvance) {
        currentState = CURRENT_STATE_PREPARING_CHANGING_URL;
        this.currentUrlMapIndex = urlMapIndex;
        this.seekToInAdvance = seekToInAdvance;
        KHBMediaManager.CURRENT_PLAYING_URL = KHBUtils
                .getCurrentUrlFromMap(urlMap, this.currentUrlMapIndex);
        KHBMediaManager.CURRENT_PLING_LOOP = this.loop;
        KHBMediaManager.MAP_HEADER_DATA = this.headData;
        KHBMediaManager.instance().prepare();
    }

    public void onStatePrepared() {
        // 因为这个紧接着就会进入播放状态，所以不设置state
        isVideoRendingStart = true;
        if (currentPlayMode == PLAY_MODE_MUTE) {
            KHBMediaManager.instance().mediaPlayer.setVolume(0f, 0f);
        } else {
            KHBMediaManager.instance().mediaPlayer.setVolume(1f, 1f);
        }
        if (seekToInAdvance != 0) {
            KHBMediaManager.instance().mediaPlayer.seekTo(seekToInAdvance);
            seekToInAdvance = 0;
        } else {
            int position = KHBUtils.getSavedProgress(getContext(),
                    KHBUtils.getCurrentUrlFromMap(urlMap, currentUrlMapIndex));
            if (position != 0) {
                KHBMediaManager.instance().mediaPlayer.seekTo(position);
            }
        }
    }

    public void onStatePlaying() {
        // CWLog.i(TAG, "onStatePlaying " + " [" + this.hashCode() + "] ");
        currentState = CURRENT_STATE_PLAYING;
        startProgressTimer();
    }

    public void onStatePause() {
        // CWLog.i(TAG, "onStatePause " + " [" + this.hashCode() + "] ");
        currentState = CURRENT_STATE_PAUSE;
        startProgressTimer();
    }

    public void onStateError() {
        // CWLog.i(TAG, "onStateError " + " [" + this.hashCode() + "] ");
        currentState = CURRENT_STATE_ERROR;
        cancelProgressTimer();
    }

    public void onStateAutoComplete() {
        // CWLog.i(TAG, "onStateAutoComplete " + " [" + this.hashCode() + "] ");
        currentState = CURRENT_STATE_AUTO_COMPLETE;
        cancelProgressTimer();
        progressBar.setProgress(100);
        currentTimeTextView.setText(totalTimeTextView.getText());
    }

    public void onInfo(int what, int extra) {
        // CWLog.d(TAG, "onInfo what - " + what + " extra - " + extra);
        if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
            onStatePrepared();
            onStatePlaying();
        }
    }

    public void onError(int what, int extra) {
        // CWLog.e(TAG, "onError " + what + " - " + extra + " [" +
        // this.hashCode()
        // + "] ");
        if (what != 38 && what != -38 && extra != -38) {
            onStateError();
            if (isCurrentPlay()) {
                KHBMediaManager.instance().releaseMediaPlayer();
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (currentScreen == SCREEN_WINDOW_FULLSCREEN
                || currentScreen == SCREEN_WINDOW_TINY) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
        if (widthRatio != 0 && heightRatio != 0) {
            int specWidth = MeasureSpec.getSize(widthMeasureSpec);
            int specHeight = (int) ((specWidth * (float) heightRatio)
                    / widthRatio);
            setMeasuredDimension(specWidth, specHeight);

            int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(specWidth,
                    MeasureSpec.EXACTLY);
            int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(specHeight,
                    MeasureSpec.EXACTLY);
            getChildAt(0).measure(childWidthMeasureSpec,
                    childHeightMeasureSpec);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }

    }

    public void onAutoCompletion() {
        Runtime.getRuntime().gc();
        // CWLog.i(TAG, "onAutoCompletion " + " [" + this.hashCode() + "] ");
        onEvent(KHBUserAction.ON_AUTO_COMPLETE);
        dismissVolumeDialog();
        dismissProgressDialog();
        dismissBrightnessDialog();
        cancelProgressTimer();
        onStateAutoComplete();

        if (currentScreen == SCREEN_WINDOW_FULLSCREEN
                || currentScreen == SCREEN_WINDOW_TINY) {
            backPress();
        }
        KHBMediaManager.instance().mediaPlayer.release();
        KHBUtils.saveProgress(getContext(),
                KHBUtils.getCurrentUrlFromMap(urlMap, currentUrlMapIndex), 0);
    }

    public void onCompletion() {
        // CWLog.i(TAG, "onCompletion " + " [" + this.hashCode() + "] ");
        if (currentState == CURRENT_STATE_PLAYING
                || currentState == CURRENT_STATE_PAUSE) {
            int position = getCurrentPositionWhenPlaying();
            KHBUtils.saveProgress(getContext(),
                    KHBUtils.getCurrentUrlFromMap(urlMap, currentUrlMapIndex),
                    position);
        }
        cancelProgressTimer();
        onStateNormal();
        textureViewContainer.removeView(KHBMediaManager.textureView);
        KHBMediaManager.instance().currentVideoWidth = 0;
        KHBMediaManager.instance().currentVideoHeight = 0;

        AudioManager mAudioManager = (AudioManager) getContext()
                .getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
        KHBUtils.scanForActivity(getContext()).getWindow()
                .clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        clearFullscreenLayout();
        KHBUtils.setRequestedOrientation(getContext(), NORMAL_ORIENTATION);

        if (KHBMediaManager.surface != null)
            KHBMediaManager.surface.release();
        KHBMediaManager.textureView = null;
        KHBMediaManager.savedSurfaceTexture = null;
        isVideoRendingStart = false;
    }

    public void release() {
        if (KHBUtils.getCurrentUrlFromMap(urlMap, currentUrlMapIndex)
                .equals(KHBMediaManager.CURRENT_PLAYING_URL)
                && (System.currentTimeMillis()
                - CLICK_QUIT_FULLSCREEN_TIME) > FULL_SCREEN_NORMAL_DELAY) {
            // 在非全屏的情况下只能backPress()
            if (KHBVideoPlayerManager.getSecondFloor() != null
                    && KHBVideoPlayerManager
                    .getSecondFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN) {// 点击全屏
            } else if (KHBVideoPlayerManager.getSecondFloor() == null
                    && KHBVideoPlayerManager.getFirstFloor() != null
                    && KHBVideoPlayerManager
                    .getFirstFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN) {// 直接全屏
            } else {
                // CWLog.d(TAG, "release [" + this.hashCode() + "]");
                releaseAllVideos();
            }
        }
    }

    public void initTextureView() {
        removeTextureView();
        KHBMediaManager.textureView = new KHBResizeTextureView(getContext());
        KHBMediaManager.textureView
                .setSurfaceTextureListener(KHBMediaManager.instance());
    }

    public void addTextureView() {
        // CWLog.d(TAG, "addTextureView [" + this.hashCode() + "] ");
        LayoutParams layoutParams = new LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER);
        textureViewContainer.addView(KHBMediaManager.textureView, layoutParams);
    }

    public void removeTextureView() {
        KHBMediaManager.savedSurfaceTexture = null;
        if (KHBMediaManager.textureView != null
                && KHBMediaManager.textureView.getParent() != null) {
            ((ViewGroup) KHBMediaManager.textureView.getParent())
                    .removeView(KHBMediaManager.textureView);
        }
    }

    public void clearFullscreenLayout() {
        ViewGroup vp = (ViewGroup) (KHBUtils.scanForActivity(getContext()))// .getWindow().getDecorView();
                .findViewById(Window.ID_ANDROID_CONTENT);
        View oldF = vp.findViewById(R.id.jz_fullscreen_id);
        View oldT = vp.findViewById(R.id.jz_tiny_id);
        if (oldF != null) {
            vp.removeView(oldF);
        }
        if (oldT != null) {
            vp.removeView(oldT);
        }
        showSupportActionBar(getContext());
    }

    public void clearFloatScreen() {
        KHBUtils.setRequestedOrientation(getContext(), NORMAL_ORIENTATION);
        showSupportActionBar(getContext());
        KHBVideoPlayer currJzvd = KHBVideoPlayerManager.getCurrentJzvd();
        currJzvd.textureViewContainer.removeView(KHBMediaManager.textureView);
        ViewGroup vp = (ViewGroup) (KHBUtils.scanForActivity(getContext()))// .getWindow().getDecorView();
                .findViewById(Window.ID_ANDROID_CONTENT);
        vp.removeView(currJzvd);
        KHBVideoPlayerManager.setSecondFloor(null);
    }

    public void onVideoSizeChanged() {
        // CWLog.i(TAG, "onVideoSizeChanged " + " [" + this.hashCode() + "] ");
        if (KHBMediaManager.textureView != null) {
            KHBMediaManager.textureView
                    .setVideoSize(KHBMediaManager.instance().getVideoSize());
        }
    }

    public void startProgressTimer() {
        // CWLog.e(TAG, "startProgressTimer: ");
        cancelProgressTimer();
        UPDATE_PROGRESS_TIMER = new Timer();
        mProgressTimerTask = new ProgressTimerTask();
        UPDATE_PROGRESS_TIMER.schedule(mProgressTimerTask, 0, 300);
    }

    public void cancelProgressTimer() {
        if (UPDATE_PROGRESS_TIMER != null) {
            UPDATE_PROGRESS_TIMER.cancel();
        }
        if (mProgressTimerTask != null) {
            mProgressTimerTask.cancel();
        }
    }

    public void setProgressAndText(int progress, int position, int duration) {
        // CWLog.d(TAG, "setProgressAndText: progress=" + progress + "
        // position="
        // + position + " duration=" + duration);
        if (!mTouchingProgressBar) {
            if (progress != 0)
                progressBar.setProgress(progress);
        }
        if (position != 0)
            currentTimeTextView.setText(KHBUtils.stringForTime(position));
        totalTimeTextView.setText(KHBUtils.stringForTime(duration));
    }

    public void setBufferProgress(int bufferProgress) {
        if (bufferProgress != 0)
            progressBar.setSecondaryProgress(bufferProgress);
    }

    public void resetProgressAndTime() {
        progressBar.setProgress(0);
        progressBar.setSecondaryProgress(0);
        currentTimeTextView.setText(KHBUtils.stringForTime(0));
        totalTimeTextView.setText(KHBUtils.stringForTime(0));
    }

    public int getCurrentPositionWhenPlaying() {
        int position = 0;
        if (KHBMediaManager.instance().mediaPlayer == null)
            return position;// 这行代码不应该在这，如果代码和逻辑万无一失的话，心头之恨呐
        if (currentState == CURRENT_STATE_PLAYING
                || currentState == CURRENT_STATE_PAUSE) {
            try {
                position = KHBMediaManager.instance().mediaPlayer
                        .getCurrentPosition();
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return position;
            }
        }
        return position;
    }

    public int getDuration() {
        int duration = 0;
        if (KHBMediaManager.instance().mediaPlayer == null)
            return duration;
        try {
            duration = KHBMediaManager.instance().mediaPlayer.getDuration();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return duration;
        }
        return duration;
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // CWLog.i(TAG, "bottomProgress onStartTrackingTouch [" +
        // this.hashCode()
        // + "] ");
        cancelProgressTimer();
        ViewParent vpdown = getParent();
        while (vpdown != null) {
            vpdown.requestDisallowInterceptTouchEvent(true);
            vpdown = vpdown.getParent();
        }
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // CWLog.i(TAG, "bottomProgress onStopTrackingTouch [" + this.hashCode()
        // + "] ");
        onEvent(KHBUserAction.ON_SEEK_POSITION);
        startProgressTimer();
        ViewParent vpup = getParent();
        while (vpup != null) {
            vpup.requestDisallowInterceptTouchEvent(false);
            vpup = vpup.getParent();
        }
        if (currentState != CURRENT_STATE_PLAYING
                && currentState != CURRENT_STATE_PAUSE)
            return;
        int time = seekBar.getProgress() * getDuration() / 100;
        KHBMediaManager.instance().mediaPlayer.seekTo(time);
        // CWLog.i(TAG, "seekTo " + time + " [" + this.hashCode() + "] ");
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
                                  boolean fromUser) {
    }

    public void startWindowFullscreen() {
        // CWLog.i(TAG, "startWindowFullscreen " + " [" + this.hashCode() + "]
        // ");
        hideSupportActionBar(getContext());
        KHBUtils.setRequestedOrientation(getContext(), FULLSCREEN_ORIENTATION);

        ViewGroup vp = (ViewGroup) (KHBUtils.scanForActivity(getContext()))// .getWindow().getDecorView();
                .findViewById(Window.ID_ANDROID_CONTENT);
        View old = vp.findViewById(R.id.jz_fullscreen_id);
        if (old != null) {
            vp.removeView(old);
        }
        textureViewContainer.removeView(KHBMediaManager.textureView);
        try {
            Constructor<KHBVideoPlayer> constructor = (Constructor<KHBVideoPlayer>) KHBVideoPlayer.this
                    .getClass().getConstructor(Context.class);
            KHBVideoPlayer khbVideoPlayer = constructor
                    .newInstance(getContext());
            khbVideoPlayer.setId(R.id.jz_fullscreen_id);
            LayoutParams lp = new LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            vp.addView(khbVideoPlayer, lp);
            khbVideoPlayer
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                            | View.SYSTEM_UI_FLAG_FULLSCREEN);
            khbVideoPlayer.setUp(urlMap, currentUrlMapIndex,
                    KHBVideoPlayerStandard.SCREEN_WINDOW_FULLSCREEN, currentPlayMode, objects);
            khbVideoPlayer.setState(currentState);
            khbVideoPlayer.addTextureView();
            KHBVideoPlayerManager.setSecondFloor(khbVideoPlayer);
            // final Animation ra = AnimationUtils.loadAnimation(getContext(),
            // R.anim.start_fullscreen);
            // jzVideoPlayer.setAnimation(ra);
            onStateNormal();
            khbVideoPlayer.progressBar
                    .setSecondaryProgress(progressBar.getSecondaryProgress());
            khbVideoPlayer.startProgressTimer();
            CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startWindowTiny() {
        // CWLog.i(TAG, "startWindowTiny " + " [" + this.hashCode() + "] ");
        onEvent(KHBUserAction.ON_ENTER_TINYSCREEN);
        if (currentState == CURRENT_STATE_NORMAL
                || currentState == CURRENT_STATE_ERROR)
            return;
        ViewGroup vp = (ViewGroup) (KHBUtils.scanForActivity(getContext()))// .getWindow().getDecorView();
                .findViewById(Window.ID_ANDROID_CONTENT);
        View old = vp.findViewById(R.id.jz_tiny_id);
        if (old != null) {
            vp.removeView(old);
        }
        textureViewContainer.removeView(KHBMediaManager.textureView);

        try {
            Constructor<KHBVideoPlayer> constructor = (Constructor<KHBVideoPlayer>) KHBVideoPlayer.this
                    .getClass().getConstructor(Context.class);
            KHBVideoPlayer KHBVideoPlayer = constructor
                    .newInstance(getContext());
            KHBVideoPlayer.setId(R.id.jz_tiny_id);
            LayoutParams lp = new LayoutParams(400, 400);
            lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;
            vp.addView(KHBVideoPlayer, lp);
            KHBVideoPlayer.setUp(urlMap, currentUrlMapIndex,
                    KHBVideoPlayerStandard.SCREEN_WINDOW_TINY, currentPlayMode, objects);
            KHBVideoPlayer.setState(currentState);
            KHBVideoPlayer.addTextureView();
            KHBVideoPlayerManager.setSecondFloor(KHBVideoPlayer);
            onStateNormal();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isCurrentPlay() {
        // 不仅正在播放的url不能一样，并且各个清晰度也不能一样
        return isCurrentJZVD()
                && urlMap.containsValue(KHBMediaManager.CURRENT_PLAYING_URL);
    }

    public boolean isCurrentJZVD() {
        return KHBVideoPlayerManager.getCurrentJzvd() != null
                && KHBVideoPlayerManager.getCurrentJzvd() == this;
    }

    // 退出全屏和小窗的方法
    public void playOnThisJzvd() {
        // CWLog.i(TAG, "playOnThisJzvd " + " [" + this.hashCode() + "] ");
        // 1.清空全屏和小窗的jzvd
        currentState = KHBVideoPlayerManager.getSecondFloor().currentState;
        currentUrlMapIndex = KHBVideoPlayerManager
                .getSecondFloor().currentUrlMapIndex;
        clearFloatScreen();
        // 2.在本jzvd上播放
        setState(currentState);
        addTextureView();
    }

    // 重力感应的时候调用的函数，
    public void autoFullscreen(float x) {
        if (isCurrentPlay() && currentState == CURRENT_STATE_PLAYING
                && currentScreen != SCREEN_WINDOW_FULLSCREEN
                && currentScreen != SCREEN_WINDOW_TINY) {
            if (x > 0) {
                KHBUtils.setRequestedOrientation(getContext(),
                        ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            } else {
                KHBUtils.setRequestedOrientation(getContext(),
                        ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
            }
            onEvent(KHBUserAction.ON_ENTER_FULLSCREEN);
            startWindowFullscreen();
        }
    }

    public void autoQuitFullscreen() {
        if ((System.currentTimeMillis() - lastAutoFullscreenTime) > 2000
                && isCurrentPlay() && currentState == CURRENT_STATE_PLAYING
                && currentScreen == SCREEN_WINDOW_FULLSCREEN) {
            lastAutoFullscreenTime = System.currentTimeMillis();
            backPress();
        }
    }

    public void onEvent(int type) {
        if (JZ_USER_EVENT != null && isCurrentPlay() && urlMap != null) {
            JZ_USER_EVENT.onEvent(type,
                    KHBUtils.getCurrentUrlFromMap(urlMap, currentUrlMapIndex),
                    currentScreen, objects);
        }
    }

    public static void onScrollAutoTiny(AbsListView view, int firstVisibleItem,
                                        int visibleItemCount, int totalItemCount) {
        int lastVisibleItem = firstVisibleItem + visibleItemCount;
        int currentPlayPosition = KHBMediaManager.instance().positionInList;
        if (currentPlayPosition >= 0) {
            if ((currentPlayPosition < firstVisibleItem
                    || currentPlayPosition > (lastVisibleItem - 1))) {
                if (KHBVideoPlayerManager.getCurrentJzvd() != null
                        && KHBVideoPlayerManager
                        .getCurrentJzvd().currentScreen != KHBVideoPlayer.SCREEN_WINDOW_TINY) {
                    // CWLog.e(TAG, "onScroll: out screen");
                    KHBVideoPlayerManager.getCurrentJzvd().startWindowTiny();
                }
            } else {
                if (KHBVideoPlayerManager.getCurrentJzvd() != null
                        && KHBVideoPlayerManager
                        .getCurrentJzvd().currentScreen == KHBVideoPlayer.SCREEN_WINDOW_TINY) {
                    // CWLog.e(TAG, "onScroll: into screen");
                    KHBVideoPlayer.backPress();
                }
            }
        }
    }

    /**
     * @param view
     * @param firstVisibleItem 表示当前屏幕显示的第一个item的位置（下标从0开始）
     * @param visibleItemCount 当前屏幕可以见到的item总数，包括没有完整显示的item
     * @param totalItemCount   则是 Item的总数，包括通过addFooterView添加的那个item
     * @param headerViewsCount 头的个数
     */
    public static void onScrollReleaseAllVideos(AbsListView view,
                                                int firstVisibleItem, int visibleItemCount, int totalItemCount,
                                                int headerViewsCount) {
        int lastVisibleItem = firstVisibleItem + visibleItemCount;
        int currentPlayPosition = KHBMediaManager.instance().positionInList
                + headerViewsCount;
        if (currentPlayPosition - headerViewsCount >= 0) {
            if ((currentPlayPosition < firstVisibleItem
                    || currentPlayPosition > (lastVisibleItem - 1))) {
                KHBVideoPlayer.releaseAllVideos();
            }
        }
    }

    // TODO 是否有用
    public void onSeekComplete() {

    }

    public void showWifiDialog(int event) {
    }

    public void showProgressDialog(float deltaX, String seekTime,
                                   int seekTimePosition, String totalTime, int totalTimeDuration) {
    }

    public void dismissProgressDialog() {

    }

    public void showVolumeDialog(float deltaY, int volumePercent) {

    }

    public void dismissVolumeDialog() {

    }

    public void showBrightnessDialog(int brightnessPercent) {

    }

    public void dismissBrightnessDialog() {

    }

    public static class JZAutoFullscreenListener implements SensorEventListener {
        @Override
        public void onSensorChanged(SensorEvent event) {// 可以得到传感器实时测量出来的变化值
            final float x = event.values[SensorManager.DATA_X];
            float y = event.values[SensorManager.DATA_Y];
            float z = event.values[SensorManager.DATA_Z];
            // 过滤掉用力过猛会有一个反向的大数值
            if (((x > -15 && x < -10) || (x < 15 && x > 10))
                    && Math.abs(y) < 1.5) {
                if ((System.currentTimeMillis()
                        - lastAutoFullscreenTime) > 2000) {
                    if (KHBVideoPlayerManager.getCurrentJzvd() != null) {
                        KHBVideoPlayerManager.getCurrentJzvd()
                                .autoFullscreen(x);
                    }
                    lastAutoFullscreenTime = System.currentTimeMillis();
                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    }

    public class ProgressTimerTask extends TimerTask {
        @Override
        public void run() {
            if (currentState == CURRENT_STATE_PLAYING
                    || currentState == CURRENT_STATE_PAUSE) {
                // CWLog.v(TAG, "onProgressUpdate " + "[" + this.hashCode() + "]
                // ");
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        int position = getCurrentPositionWhenPlaying();
                        int duration = getDuration();
                        int progress = position * 100
                                / (duration == 0 ? 1 : duration);
                        setProgressAndText(progress, position, duration);
                    }
                });
            }
        }
    }

    public void setViewPostVideo(boolean isView, String topicPostId) {
        this.isViewPostVideo = isView;
        this.topicPostId = topicPostId;
    }

    public void setViewPostVideo(boolean isView, String topicPostId, int type) {
        this.isViewPostVideo = isView;
        this.topicPostId = topicPostId;
        this.type = type;
    }

//    public static String packagePlayMusicUtils = "com.ciwong.xixin.modules.topic.util.PlayMusicUtils";
//
//    private void stopMusic()
//    {
//        try
//        {
//            Class packclass = Class.forName(packagePlayMusicUtils);
//            if (packclass == null)
//            {
//                return;
//            }
//            Method jumpShareBrowser = packclass.getMethod("stopMusic");
//            jumpShareBrowser.invoke(packclass);
//        }
//        catch (Exception e)
//        {
//            e.printStackTrace();
//        }
//    }

}
